package com.yxkj.railservicer.pager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.classic.ClassicRefreshView;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.activity.LoginActivity;
import com.yxkj.railservicer.activity.MainActivity;
import com.yxkj.railservicer.adapter.QiangDanAdapter;
import com.yxkj.railservicer.bean.QiangDanBean;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.StringUtil;

import org.bouncycastle.asn1.esf.SPuri;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by sunyu on 2017/2/28.
 */

public class QiangDan extends BasePager implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    private static final String TAG = "TAG";

    private MainActivity mainActivity;
    private View view;
    private RecyclerView can_content_view;
    private QiangDanAdapter adapter;
    private List<QiangDanBean> list;
    private OkHttpClient client;
    private CanRefreshLayout refresh;
    private ClassicRefreshView can_refresh_header;
    private ClassicRefreshView can_refresh_footer;

    private List<String> idList; //订单id

    private JSONUtil jsonUtil;
    private ProgressDialog dialog;


    public QiangDan(Activity activity) {
        super(activity);
        this.mainActivity = (MainActivity) activity;
    }

    @Override
    public void initData() {
        super.initData();
        if (view == null) {
            view = View.inflate(activity, R.layout.pager_base, null);

            can_content_view = (RecyclerView) view.findViewById(R.id.can_content_view);
            LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
            can_content_view.setLayoutManager(layoutManager);

            jsonUtil = new JSONUtil();

            client = new OkHttpClient();


            can_refresh_header = (ClassicRefreshView) view.findViewById(R.id.can_refresh_header);
            can_refresh_footer = (ClassicRefreshView) view.findViewById(R.id.can_refresh_footer);

            can_refresh_header.setRefreshingStr("正在刷新");
            can_refresh_header.setPullStr("下拉刷新");
            can_refresh_header.setReleaseStr("松手刷新");
            can_refresh_header.setCompleteStr("刷新完成");

            can_refresh_footer.setRefreshingStr("正在加载");
            can_refresh_footer.setPullStr("上拉加载");
            can_refresh_footer.setReleaseStr("松手加载更多");
            can_refresh_footer.setCompleteStr("加载完成");

            refresh = (CanRefreshLayout) view.findViewById(R.id.refresh);
            //下拉刷新
            refresh.setOnRefreshListener(this);
            //上拉加载
            refresh.setOnLoadMoreListener(this);
            //刷新样式
            refresh.setStyle(0, 0);

            idList = new ArrayList<>();

            list = new ArrayList<>();
            adapter = new QiangDanAdapter(activity, list, this);

            can_content_view.setAdapter(adapter);

            fl_basepager.addView(view);
            getInfo1();
        } else {
            onRefresh();
        }

    }

    /**
     * 抢单
     */
    public void acceptOrder(final int position) {
        dialog = ProgressDialog.show(activity, "提示", "正在抢单");
        String message = "?orderId=" + idList.get(position);

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.acceptOrder_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    final JSONObject jsonObject = JSON.parseObject(jsonData);

                    list.remove(position);
                    idList.remove(position);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mainActivity.getCount(QiangDan.this, list.size() + "");
                            mainActivity.basePagers.get(1).initData();
                            adapter.notifyDataSetChanged();
                        }
                    });
                    toast(jsonObject.getString("message"));
                }
                dismiss();
                Log.e(TAG, "抢单联网成功" + jsonData);
            }
        });
    }

    private String orderStatus;
    private String count; //是否统计总数
    private int offset;//从哪一条之后开始取
    private int limit;//一次最多取多少条
    private String token;
    private String total;

    /**
     * 查询订单信息
     */
    private void getInfo() {

        if (0 == pages) {
            list.clear();
            idList.clear();
//            adapter.notifyDataSetChanged();
        }

        token = SPUtil.getString(activity, "token");
        orderStatus = "7020";
        count = "true";
        limit = 20;
        offset = pages * limit;


        RequestBody body = new FormBody.Builder()
                .add("orderStatus", orderStatus)
                .add("count", count)
                .add("offset", String.valueOf(offset))
                .add("limit", String.valueOf(limit))
                .build();
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.query_url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray rows = jsonObject.getJSONObject("data").getJSONArray("rows");
                        total = jsonObject.getJSONObject("data").getString("total");
                        for (int i = 0; i < rows.size(); i++) {
                            JSONObject o = rows.getJSONObject(i);
                            String mainOrderId = o.getString("mainOrderId");
                            idList.add(mainOrderId);
                            list.add(new QiangDanBean(o));
                        }

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mainActivity.getCount(QiangDan.this, total);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                });

                Log.e(TAG, "查询联网成功" + jsonData);
            }
        });

    }

    public void getInfo1() {
        if (0 == pages) {
            list.clear();
            idList.clear();
            adapter.notifyDataSetChanged();
        }
        token = SPUtil.getString(activity, "token");
        orderStatus = "7020";
        count = "true";
        limit = 20;
        offset = pages * limit;


        RequestBody body = new FormBody.Builder()
                .add("orderStatus", orderStatus)
                .add("count", count)
                .add("offset", String.valueOf(offset))
                .add("limit", String.valueOf(limit))
                .build();
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.query_url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray rows = jsonObject.getJSONObject("data").getJSONArray("rows");
                        total = jsonObject.getJSONObject("data").getString("total");
                        for (int i = 0; i < rows.size(); i++) {
                            JSONObject o = rows.getJSONObject(i);
                            String mainOrderId = o.getString("mainOrderId");
                            idList.add(mainOrderId);
                            list.add(new QiangDanBean(o));
                        }

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mainActivity.getCount(QiangDan.this, total);
                        adapter.notifyDataSetChanged();
                    }
                });

                Log.e(TAG, "查询联网成功" + jsonData);
            }
        });

    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    @Override
    public void onRefresh() {
        dialog = ProgressDialog.show(activity, "提示", "正在查询订单，请稍等");
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                String a = SPUtil.getString(activity, "isBusy");
                Log.e(TAG, "++++++++++" + a);
                if (!"关闭".equals(SPUtil.getString(activity, "isBusy"))) {
                    pages = 0;
//                    list.clear();
//                    idList.clear();
                    getInfo();
                }
                refresh.refreshComplete();
            }
        }, 1000);
    }

    private int pages;

    @Override
    public void onLoadMore() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                String a = SPUtil.getString(activity, "isBusy");
                Log.e(TAG, "++++++++++" + a);
                if (!"关闭".equals(SPUtil.getString(activity, "isBusy"))) {
                    pages++;
                    getInfo();
                    can_refresh_footer.setCompleteStr("");
                }
                refresh.loadMoreComplete();
            }
        }, 1000);

    }

    private void toast(final String string) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(activity, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }
}
